package com.shell.arouter.extend

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch

/**
 * 说明：CoroutineScope
 * <p/>
 * 作者：Fanly
 * <p/>
 * 类型：Class
 * <p/>
 * 时间：2020/04/29 10:42
 * <p/>
 * 版本：version 1.0
 */
fun CoroutineScope.tryLaunch(error: ((Throwable) -> Unit)? = null, block: suspend CoroutineScope.() -> Unit): Job {
    return launch(Dispatchers.Main) {
        try {
            block.invoke(this)
        } catch (e: Throwable) {
            error?.invoke(e)
        }
    }
}

fun CoroutineScope.tryLaunchIO(error: ((Throwable) -> Unit)? = null, block: suspend CoroutineScope.() -> Unit): Job {
    return launch(Dispatchers.IO) {
        try {
            block.invoke(this)
        } catch (e: Throwable) {
            error?.invoke(e)
        }
    }
}